<?php
namespace app\common\service;

use app\common\util\Util;
use think\Model;

class MediaFolderService extends BaseService
{

    /**
     * 添加文件夹目录，仅添加层级关系，文件名由重命名接口提供
     * @param $sid
     * @param $parent_id
     */
    public function addFolder($sid, $parent_id, $name){
        $data = [
            'sid' => $sid,
            'parent_id' => $parent_id,
            'name' => $name,
            'status' => 1
        ];
        $id = db('media_folder')->insertGetId($data);
        if($id){
            return ['status' => 1, 'msg' => '添加成功', 'data' =>['content' => ['id' => $id]]];
        } else {
            return ['status' => 0, 'msg' => '添加失败'];
        }
    }

    /**
     * 重命名文件夹名
     * @param $sid
     * @param $id
     * @param $name
     * @return int
     */
    public function renameFolder($sid, $id, $name){
        return db('media_folder')->where(['sid' => $sid, 'id' => $id])->setField('name', $name);
    }


    /**
     * 删除文件夹
     * @param $sid
     * @param $id
     * @param int $type
     * @return bool
     */
    public function deleteFolder($sid, $id, $type = 1){
        //获取子文件夹id
        $children = db('media_folder')->where(['sid' => $sid, 'parent_id' => $id, 'status' => 1])->select();
        $ids = [];
        if($children){
            foreach($children as $k => $v){
                $ids[$k] = $v['id'];
            }
        }
        array_push($ids, $id);

        //开启事务处理
        db()->startTrans();
        try{
            //删除该文件夹及其子文件夹目录
            db('media_folder')->where(['sid' => $sid, 'id' => ['in', $ids]])->setField('status', -1);
            //判断是否删除文件夹下图片
            if($type == 1){
                //不删除  则将该文件夹及其子文件夹下的图片所属分类置为0
                db('media')->where(['sid' => $sid, 'fid' => ['in', $ids]])->setField('fid',0);
            } elseif ($type == 2){
                //软删除
                db('media')->where(['sid' => $sid, 'fid' => ['in', $ids]])->setField('status', -1);
            }
            db()->commit();
            return true;
        } catch (\Exception $e){
            db()->rollback();
            return false;
        }
    }

    /**
     * 返回树形结构的文件夹目录
     * @param $sid
     * @return array
     */
    public function getFolderListTree($sid){
        $list = db('media_folder')->field('id,name,parent_id')->where(['sid' => $sid, 'status' => 1])->select();
        $list_tree = Util::list_to_tree($list, 'id', 'parent_id', 'children', 0);
        return ['content' => $list_tree];
    }
}